﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VueShopApi.Common;
using VueShopApi.Dtos;
using VueShopApi.Entities;

namespace VueShopApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RightsController : AuthorizeController
    {
        private readonly ILogger<RightsController> _logger;
        private readonly IFreeSql _context;

        public RightsController(ILogger<RightsController> logger, IFreeSql context)
        {
            _logger = logger;
            _context = context;
        }

        [HttpGet("{type}")]
        public async Task<IActionResult> GetAllRights([FromRoute] string type)
        {
            var permissions = await _context.Select<SpPermissionApi, SpPermission>()
               .LeftJoin((api, main) => main.PsId == api.PsId)
               .ToListAsync<PermissionApiIncludePermissionDto>();

            if (type == "list")
            {
                var list = permissions.Select(permission => new PermissionListDto
                {
                    Id = permission.PsId,
                    AuthName = permission.PsName,
                    Level = permission.PsLevel + "",
                    Pid = permission.PsPid + "",
                    Path = permission.PsApiPath
                }).OrderBy(p => p.Level).ToList();
                return ServerResponse.Yes(list);
            }
            else if (type == "tree")
            {
                var tree = GetPermissionsTree(permissions);
                return ServerResponse.Yes(tree);
            }
            else
            {
                return ServerResponse.BadRequest("参数类型错误");
            }
        }
    }
}
